<?php

namespace app\admin\controller;

class Video extends Base
{
    public function all()
    {
        $videos = model('Video')->order(['is_top' => 'asc', 'create_time' => 'desc'])->paginate(10);
        $viewData = [
            'videos' => $videos
        ];
        $this->assign($viewData);
        return view();
    }

    public function add()
    {
        if (request()->isAjax()) {
            $data = [
                'title' => input('post.title'),
                'sort' => input('post.sort'),
                'is_top' => input('post.is_top'),
                'author' => session('admin.nickname')
            ];
            $result = model('Video')->add($data);
            if ($result == 1) {
                $this->success('添加成功！', 'admin/video/all');
            }else {
                $this->error($result);
            }
        }
        return view();
    }

    public function top()
    {
        $videoInfo = model('Video')->find(input('post.id'));
        $videoInfo->is_top = input('post.is_top') ? 0 : 1;
        $result = $videoInfo->save();
        if ($result) {
            $this->success('操作成功！', 'admin/video/all');
        }else {
            $this->error('操作失败！');
        }
    }

    public function edit()
    {
        if (request()->isAjax()) {
            $data = [
                'id' => input('post.id'),
                'title' => input('post.title')
            ];
            $result = model('Video')->edit($data);
            if ($result == 1) {
                $this->success('编辑成功！', 'admin/video/all');
            }else {
                $this->error($result);
            }
        }
        $videoInfo = model('Video')->find(input('id'));
        $viewData = [
            'videoInfo' => $videoInfo
        ];
        $this->assign($viewData);
        return view();
    }

    public function sort()
    {
        $videoInfo = model('Video')->find(input('post.id'));
        $videoInfo->sort = input('post.sort');
        $result = $videoInfo->save();
        if ($result) {
            $this->success('操作成功！', 'admin/video/all');
        }else {
            $this->error('操作失败！');
        }
    }

    public function del()
    {
        $videoInfo = model('Video')->with('video_list')->find(input('post.id'));
        $result = $videoInfo->together('video_list')->delete();
        if ($result) {
            $this->success('删除成功！', 'admin/video/all');
        }else {
            $this->error('删除失败！');
        }
    }
}
